
package com.edu.controller;



import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.edu.entity.Admins;
import com.edu.entity.ArticleAndUserCount;
import com.edu.entity.Articles;
import com.edu.entity.Users;
import com.edu.service.impl.AdminServiceImpl;
import com.edu.service.impl.ArticleServiceImpl;
import com.edu.service.impl.UsersServiceImpl;
import com.edu.util.PageData;
import com.edu.util.VerifyCode;
import com.google.gson.Gson;

/**
 * @author 陆亮
 * Servlet implementation class EduControllerByLu
 */
@WebServlet("/EduControllerByLu")
public class EduControllerByLu extends HttpServlet {
	private static final long serialVersionUID = 1L;
	AdminServiceImpl adminService = new AdminServiceImpl();
	ArticleServiceImpl articleService = new ArticleServiceImpl();
	UsersServiceImpl usersService = new UsersServiceImpl();
	VerifyCode vc = new VerifyCode();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EduControllerByLu() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op=request.getParameter("op");
		HttpSession session=request.getSession();
		Object obj=session.getAttribute("users");
		if (null != obj) {
			if ("queryArticlesFor5".equals(op)) {
				//后台首页显示文章
				getFiveArticles(request,response);
			}else if ("queryUsers".equals(op)) {
				//查询所有用户
				getAllUsers(request,response);
				request.getRequestDispatcher("mvc/userstable.jsp").forward(request, response);
			}else if ("writeoutarticle".equals(op)) {
				String articleId=request.getParameter("articleid");
				articleService.outArticle(Integer.valueOf(articleId));
				getAllArticle(request,response);
			}else if ("writeinarticle".equals(op)) {
				String articleId=request.getParameter("articleid");
				articleService.inArticle(Integer.valueOf(articleId));
				getAllArticle(request,response);
			}else if ("queryCount".equals(op)) {
				//查询文章与用户的总数量与新增数
				getCount(request,response);
			}else if ("getnewCount".equals(op)) {
				//获取图标所需数据--文章近7日新增
				getnewCount(request, response);
			}else if ("getnewUserCount".equals(op)) {
				get7dayUsers(request, response);
			}else if ("gettypeCount".equals(op)) {
				getTypeCount(request, response);
			}else if ("getAllArticle".equals(op)) {
				//后台显示
				getAllArticle(request, response);
			}else if ("queryarticle".equals(op)) {
				//查询全部文章,分页显示前台
				getAllArticles(request,response);
			}else if ("checkAdmin".equals(op)) {
				//后台添加管理员的时候,进行检查
				checkAdmin(request,response);
			}else if ("doPay".equals(op)) {
				doPay(request, response);
			}else if ("returnUrl".equals(op)) {
				try {
					returnUrl(request, response);
				} catch (AlipayApiException e) {
					// TODO Auto-generated catch block
					System.out.println("返回出了问题");
				}
			}
		}else if ("adminLogin".equals(op)) {
			adminLogin(request,response,session);
		}else if ("getImg".equals(op)) {
			//获取登录页面的验证码图片
			getImg(request,response);
		}else if ("getImgText".equals(op)) {
			//获取登录界面的验证码信息
			getText(request,response);
		}else if ("addminExit".equals(op)) {
			// 退出系统,清除session中用户的信息
			request.getSession().removeAttribute("users");
			// 重定向
			response.sendRedirect("mvc/login.jsp");
		}else if ("queryarticle".equals(op)) {
			//查询全部文章,分页显示,前台显示
			getAllArticles(request,response);
			//注销文章
		}else if ("getTypeName".equals(op)) {
			//前台获取类型名
			getTypes(request, response);
		}else if ("getGoodWord".equals(op)) {
			//获取心灵鸡汤
			getGoodWord(request, response);
		}else if ("doPay".equals(op)) {
			doPay(request, response);
		}else if ("returnUrl".equals(op)) {
			try {
				returnUrl(request, response);
			} catch (AlipayApiException e) {
				// TODO Auto-generated catch block
				System.out.println("返回出了问题");
			}
		}else {
			 response.sendRedirect("mvc/login.jsp");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * 管理员登录方法
	 * @param adminAccount 管理员账户
	 * @param adminPwd 管理员密码
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminLogin(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException {
		response.setContentType("text/html");
		String adminAccount=request.getParameter("username");
		String adminPwd=request.getParameter("password");
		Admins admins=adminService.getAdminsByNameandPwd(adminAccount, adminPwd);
		if (admins != null) {
			String checked=request.getParameter("remberme");
			if (null != checked) {
				//cookie记住密码,先获取选择框
				Cookie cookie1 = new Cookie("adminAccount",adminAccount);
				Cookie cookie2 = new Cookie("adminPwd",adminPwd);
				Cookie cookie3 = new Cookie("checked","checked");
				//设置cookie周期
				cookie1.setMaxAge(7*24*60*60);
				cookie2.setMaxAge(7*24*60*60);
				cookie3.setMaxAge(7*24*60*60);
				//保存cookie,去jsp页面取值
				response.addCookie(cookie1);response.addCookie(cookie2);response.addCookie(cookie3);
			}
			//把user信息存在session里面
			session.setAttribute("users", admins);
			/*request.getRequestDispatcher("ArticleController?op=query").forward(request, response);	*/
			request.getRequestDispatcher("mvc/index.jsp").forward(request, response);
		} else {
            response.getWriter().print("<script>alert('用户名或密码错误')</script>");
            response.sendRedirect("mvc/login.jsp");
		}
	}
	
	private void getFiveArticles(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Articles> list=articleService.queryTopArticles();
		Gson gson = new Gson();
		String articlejson=gson.toJson(list);
		response.getWriter().print(articlejson);
		response.getWriter().close();
	}
	
	private void getAllUsers(HttpServletRequest request, HttpServletResponse response) {
		List<Users> list=usersService.getAllUsers();
		request.setAttribute("userslist", list);
	}
	
	private void getAllArticles(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//如果没有值,则默认为第1条开始,每页3条信息,查询所有
				int pageNo=1;
				int pageSize=10;
				String titleKey="";
				String typeName="";
				if (request.getParameter("pageNo")!=null) {
					pageNo=Integer.parseInt(request.getParameter("pageNo"));
				}
				if (request.getParameter("pageSize")!=null) {
					pageSize=Integer.parseInt(request.getParameter("pageSize"));
				}
				if (request.getParameter("titleKey")!=null) {
					titleKey=request.getParameter("titleKey");
				}
				if (request.getParameter("typeKey")!=null) {
					typeName=request.getParameter("typeKey");
				}
					PageData pagedata=articleService.getAllArticlesByTypes(pageNo, pageSize, typeName, titleKey);
					Gson gson = new Gson();
					response.getWriter().print(gson.toJson(pagedata));
					response.getWriter().close();
	}
	private void getCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ArticleAndUserCount count=null;
		int newUsers=usersService.getNewUser();
		int allUsers=usersService.getUsersCount();
		int newArt=articleService.getNewArticlecount();
		int allArt=articleService.getAllArticlecount();
		count = new ArticleAndUserCount(newArt,allArt,newUsers,allUsers);
		if (count != null) {
			Gson gson = new Gson();
			response.getWriter().print(gson.toJson(count));
			response.getWriter().close();
		}	
	}
	private void getImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		VerifyCode.output(vc.getImage(), response.getOutputStream());
	}
	
	private void getText(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		String text=vc.getText().toLowerCase();
		System.out.println(text);
		response.getWriter().print(text);
		response.getWriter().close();
	}
	
	private void getnewCount(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		System.out.println("看看走没走这步");
		int[]sum=articleService.get7DayArticles();
		System.out.println(sum.length);
		for (int i = 0; i < sum.length; i++) {
			System.out.println(sum[i]);
		}
		Gson gon = new Gson();
		response.getWriter().print(gon.toJson(sum));
		response.getWriter().close();
	}
	
	private void get7dayUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int[]sum=usersService.get7DayAtricles();		
		Gson gon = new Gson();
		response.getWriter().print(gon.toJson(sum));
		response.getWriter().close();
	}
	
	private void getTypes(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<String> list=articleService.getTypeName();
		Gson gon = new Gson();
		response.getWriter().print(gon.toJson(list));
		response.getWriter().close();
	}
	
	private void getTypeCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int[]sum=articleService.getTypeArticles();
		Gson gon = new Gson();
		response.getWriter().print(gon.toJson(sum));
		response.getWriter().close();
	}
	private void getAllArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//后台显示所有文章
		int pageNo=1;
		int pageSize=8;
		String titleKey="";
		if (request.getParameter("pageNo")!=null) {
			pageNo=Integer.parseInt(request.getParameter("pageNo"));
		}
		if (request.getParameter("pageSize")!=null) {
			pageSize=Integer.parseInt(request.getParameter("pageSize"));
		}
		if (request.getParameter("titleKey")!=null) {
			titleKey=request.getParameter("titleKey");
		}
			PageData pagedata=articleService.getAllArticlesByTitle(pageNo, pageSize, titleKey);
			Gson gson = new Gson();
			response.getWriter().print(gson.toJson(pagedata));
			response.getWriter().close();
		}	
	private void getGoodWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String words=articleService.getGoodWord();
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(words));
		response.getWriter().close();
	}
	private void checkAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String adminAccount=request.getParameter("adminaccount");
		Admins admin=adminService.getByAccount(adminAccount);
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(admin));
		response.getWriter().close();
	}
	private void doPay( HttpServletRequest request2,HttpServletResponse response) {
		System.out.println("进来了");
		Random r=new Random();
        //实例化客户端,填入所需参数
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.return_url);
        request.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(r.nextInt(9)+1);
        //订单名称，必填
        String subject ="购买积分";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset="+AlipayConfig.charset);
        try {
			response.getWriter().write(form);
			response.getWriter().flush();
	        response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("出问题了");
		}// 直接将完整的表单html输出到页面
        
	}
	
	public void returnUrl(HttpServletRequest request, HttpServletResponse response)
	        throws IOException, AlipayApiException {
	    System.out.println("=================================同步回调=====================================");

	    // 获取支付宝GET过来反馈信息
	    Map<String, String> params = new HashMap<String, String>();
	    Map<String, String[]> requestParams = request.getParameterMap();
	    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
	        String name = (String) iter.next();
	        String[] values = (String[]) requestParams.get(name);
	        String valueStr = "";
	        for (int i = 0; i < values.length; i++) {
	            valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
	        }
	        // 乱码解决，这段代码在出现乱码时使用
	        valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
	        params.put(name, valueStr);
	    }

	    System.out.println(params);//查看参数都有哪些
	    boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
	    		AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名
	    //验证签名通过
	    if(signVerified){
	        // 商户订单号
	        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
	        
	        // 支付宝交易号
	        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
	        
	        // 付款金额
	        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
	        
	        System.out.println("商户订单号="+out_trade_no);
	        System.out.println("支付宝交易号="+trade_no);
	        System.out.println("付款金额="+total_amount);
	        
			//支付成功，修复支付状态
	        //payService.updateById(Integer.valueOf(out_trade_no));
	        //return "ok";//跳转付款成功页面
	        System.out.println("ok");
	    }else{
	        //return "no";//跳转付款失败页面
	    	 System.out.println("no");
	    }
	    
	}
}

